/*
 * @Author: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @Date: 2025-10-26 21:23:41
 * @LastEditors: 来自火星的码农 15122322+heyzhi@user.noreply.gitee.com
 * @LastEditTime: 2025-10-30 16:13:47
 * @FilePath: /GateServer/src/statusclient/statusconpool.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "statusconpool.h"
#include <cstddef>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
#include <memory>
#include <mutex>
#include <queue>
#include <string>
#include "../util/logger.h"

namespace Yizhi {
   StatusConPool::StatusConPool(const std::string& host, int port, size_t poolsize)
    : m_poolsize(poolsize), m_host(host), m_port(port), m_stop(false) {
    
    std::string url = m_host + ":" + std::to_string(m_port);
    
    LOG_DEBUG("Creating connection pool to: "+url);
    
    for(size_t i = 0; i < m_poolsize; i++) {
        auto channel = grpc::CreateChannel(url, grpc::InsecureChannelCredentials());
        
        // 检查连接状态
        auto state = channel->GetState(true); // 尝试连接
       // LOG_DEBUG(state);
        
        auto stub = message::GetStatusService::NewStub(channel);
        if (stub) {
            m_cons.push(std::move(stub));
            LOG_DEBUG("Successfully created connection ");
        } else {
            LOG_ERROR("Failed to create connection " );
        }
    }
    
    LOG_DEBUG( m_cons.size());
}
    StatusConPool::~StatusConPool(){
        close();
    }

    std::unique_ptr<message::GetStatusService::Stub> StatusConPool::Getconnection(){
        
        std::unique_lock<std::mutex> lock(m_mutex);

        m_cond.wait(lock,[this](){
            return m_stop||!m_cons.empty();
        });

        if(m_stop){
            return nullptr;
        }
        auto res=std::move( m_cons.front());
        m_cons.pop();
        return res;

    }

    void StatusConPool::ReturnCon(std::unique_ptr<message::GetStatusService::Stub> con){
        std::lock_guard<std::mutex>lock(m_mutex);
        if(m_stop){
            return;
        }
        m_cons.push(std::move(con));
        m_cond.notify_one();
    }
    void StatusConPool::close(){
        std::lock_guard<std::mutex>lock(m_mutex);
        while(!m_cons.empty()){
            m_cons.pop();
        }
        
        m_stop=true;
        m_cond.notify_all();
    }
}


